<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目编码" prop="projectCode">
        <el-input
          v-model="queryParams.projectCode"
          placeholder="请输入项目编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        <el-form-item label="项目状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择项目状态" clearable>
            <el-option
              v-for="dict in pm_project_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable>
          <el-option
            v-for="dict in pm_project_priority"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleQuery">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button size="small" @click="resetQuery">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="small"
          @click="handleAdd"
          v-hasPermi="['pm:project:add']"
        >
          <el-icon><Plus /></el-icon>新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pm:project:edit']"
        >
          <el-icon><Edit /></el-icon>修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pm:project:remove']"
        >
          <el-icon><Delete /></el-icon>删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          size="small"
          @click="handleExport"
          v-hasPermi="['pm:project:export']"
        >
          <el-icon><Download /></el-icon>导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="项目编码" align="center" prop="projectCode" />
      <el-table-column label="项目状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag 
            :options="pm_project_status || []" 
            :value="scope.row.status"
            v-if="pm_project_status && pm_project_status.length > 0"
          />
          <el-tag v-else type="info">{{ scope.row.status || '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority">
        <template #default="scope">
          <dict-tag 
            :options="pm_project_priority || []" 
            :value="scope.row.priority"
            v-if="pm_project_priority && pm_project_priority.length > 0"
          />
          <el-tag v-else type="info">{{ scope.row.priority || '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="进度" align="center" prop="progress">
        <template #default="scope">
          <el-progress :percentage="Number(scope.row.progress) || 0" :stroke-width="8"></el-progress>
        </template>
      </el-table-column>
      <el-table-column label="项目经理" align="center" prop="managerName" />
      <el-table-column label="开始日期" align="center" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="small"
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['pm:project:query']"
          >
            <el-icon><View /></el-icon>查看
          </el-button>
          <el-button
            size="small"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pm:project:edit']"
          >
            <el-icon><Edit /></el-icon>修改
          </el-button>
          <el-button
            size="small"
            type="text"
            @click="handleCopy(scope.row)"
            v-hasPermi="['pm:project:add']"
          >
            <el-icon><DocumentCopy /></el-icon>复制
          </el-button>
          <el-button
            size="small"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pm:project:remove']"
          >
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="isView ? {} : rules" label-width="80px">
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" :disabled="isView" />
        </el-form-item>
        <el-form-item label="项目编码" prop="projectCode">
          <el-input v-model="form.projectCode" placeholder="请输入项目编码" :disabled="isView" />
        </el-form-item>
        <el-form-item label="项目描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入项目描述" :disabled="isView" />
        </el-form-item>
        <el-form-item label="项目类型" prop="projectType">
          <el-select v-model="form.projectType" placeholder="请选择项目类型" :disabled="isView">
            <el-option
              v-for="dict in pm_project_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择项目状态" :disabled="isView">
            <el-option
              v-for="dict in pm_project_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择优先级" :disabled="isView">
            <el-option
              v-for="dict in pm_project_priority"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker clearable
            v-model="form.startDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开始日期"
            :disabled="isView">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker clearable
            v-model="form.endDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择结束日期"
            :disabled="isView">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预算" prop="budget">
          <el-input v-model="form.budget" placeholder="请输入预算" :disabled="isView" />
        </el-form-item>
        <el-form-item label="项目经理" prop="managerId">
          <el-select v-model="form.managerId" placeholder="请选择项目经理" clearable :disabled="isView">
            <el-option
              v-for="user in projectManagerList"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId"
            />
          </el-select>
          <div class="el-form-item__help" style="color: #909399; font-size: 12px; margin-top: 4px;">
            建议选择项目成员中的用户作为项目经理
          </div>
        </el-form-item>
        <el-form-item label="是否模板" prop="isTemplate">
          <el-radio-group v-model="form.isTemplate" :disabled="isView">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否公开" prop="isPublic">
          <el-radio-group v-model="form.isPublic" :disabled="isView">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :disabled="isView" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!isView" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">{{ isView ? '关 闭' : '取 消' }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, getCurrentInstance, watchEffect, toRefs } from 'vue'
import type { ElFormInstance } from 'element-plus'
import { listProject, getProject, delProject, addProject, updateProject, copyProject } from "@/api/pm/project";
import { listUser } from "@/api/system/user";
import { Search, Refresh, Plus, Edit, Delete, Download, View, DocumentCopy } from '@element-plus/icons-vue';

// 获取当前实例
const { proxy } = getCurrentInstance() as any

// 获取字典数据 - 使用 proxy.useDict 方式
const { pm_project_status, pm_project_priority, pm_project_type } = toRefs<any>(proxy?.useDict('pm_project_status', 'pm_project_priority', 'pm_project_type'))

console.log("pm_project_status", pm_project_status.value)
// 表单引用
const formRef = ref<ElFormInstance>()
const queryFormRef = ref<ElFormInstance>()


// 响应式数据
const loading = ref(true)
const ids = ref<number[]>([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const projectList = ref([])
const title = ref("")
const open = ref(false)
const userList = ref([])
const projectManagerList = ref([]) // 项目经理候选列表
const isView = ref(false) // 是否为查看模式

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  projectName: null,
  projectCode: null,
  status: null,
  priority: null,
  managerId: null,
  clientId: null,
  isTemplate: null,
  isPublic: null,
})

// 表单参数
const form = ref({
  projectId: null,
  projectName: null,
  projectCode: null,
  description: null,
  projectType: "normal",
  status: "planning",
  priority: "medium",
  startDate: null,
  endDate: null,
  actualStartDate: null,
  actualEndDate: null,
  progress: 0,
  budget: null,
  actualCost: null,
  managerId: null,
  clientId: null,
  templateId: null,
  isTemplate: false,
  isPublic: false,
  remark: null
})

// 表单校验
const rules = reactive({
  projectName: [
    { required: true, message: "项目名称不能为空", trigger: "blur" }
  ],
  projectCode: [
    { required: true, message: "项目编码不能为空", trigger: "blur" }
  ],
  status: [
    { required: true, message: "项目状态不能为空", trigger: "change" }
  ],
  priority: [
    { required: true, message: "优先级不能为空", trigger: "change" }
  ]
})

// 生命周期
onMounted(() => {
  getList()
  getUserList()
})

// 方法定义
/** 查询项目管理列表 */
const getList = () => {
  loading.value = true;
  listProject(queryParams).then(response => {
    projectList.value = response.rows || [];
    total.value = response.total || 0;
    loading.value = false;
  }).catch(error => {
    console.error('获取项目列表失败:', error);
    projectList.value = [];
    total.value = 0;
    loading.value = false;
  });
}

/** 查询用户列表 */
const getUserList = () => {
  listUser().then(response => {
    userList.value = response.rows || [];
    // 初始化时，项目经理候选列表包含所有用户
    projectManagerList.value = response.rows || [];
  }).catch(error => {
    console.error('获取用户列表失败:', error);
    userList.value = [];
    projectManagerList.value = [];
  });
}

/** 查询项目成员列表（用于项目经理选择） */
const getProjectMemberList = (projectId) => {
  if (!projectId) {
    projectManagerList.value = userList.value; // 如果没有项目ID，显示所有用户
    return;
  }
  
  // 这里可以调用项目成员API获取当前项目的成员列表
  // 暂时使用所有用户列表，后续可以优化
  projectManagerList.value = userList.value;
}

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
}

// 表单重置
const reset = () => {
  form.value = {
    projectId: null,
    projectName: null,
    projectCode: null,
    description: null,
    projectType: "normal",
    status: "planning",
    priority: "medium",
    startDate: null,
    endDate: null,
    actualStartDate: null,
    actualEndDate: null,
    progress: 0,
    budget: null,
    actualCost: null,
    managerId: null,
    clientId: null,
    templateId: null,
    isTemplate: false,
    isPublic: false,
    remark: null
  };
  proxy?.$nextTick(() => {
    formRef.value?.resetFields();
  });
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  proxy?.$nextTick(() => {
    queryFormRef.value?.resetFields();
  });
  handleQuery();
}

// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.projectId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  isView.value = false;
  open.value = true;
  title.value = "添加项目管理";
}

/** 查看按钮操作 */
const handleView = (row: any) => {
  reset();
  const projectId = row.projectId
  getProject(projectId).then(response => {
    form.value = response.data;
    isView.value = true;
    open.value = true;
    title.value = "查看项目管理";
  });
}

/** 修改按钮操作 */
const handleUpdate = (row: any) => {
  reset();
  const projectId = row.projectId || ids.value
  getProject(projectId).then(response => {
    form.value = response.data;
    isView.value = false;
    open.value = true;
    title.value = "修改项目管理";
  });
}

/** 复制按钮操作 */
const handleCopy = (row: any) => {
  reset();
  const projectId = row.projectId || ids.value
  getProject(projectId).then(response => {
    form.value = response.data;
    form.value.projectId = null;
    form.value.projectName = form.value.projectName + '_copy';
    open.value = true;
    title.value = "复制项目管理";
  });
}

/** 提交按钮 */
const submitForm = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.value.projectId != null) {
        updateProject(form.value).then(response => {
          proxy?.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProject(form.value).then(response => {
          proxy?.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
const handleDelete = (row: any) => {
  const projectIds = row.projectId || ids.value
  proxy?.$modal.confirm('是否确认删除项目管理编号为"' + projectIds + '"的数据项？').then(function() {
    return delProject(projectIds);
  }).then(() => {
    getList();
    proxy?.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('pm/project/export', {
    ...queryParams
  }, `project_${new Date().getTime()}.xlsx`)
}
</script>